define(function (require, exports, module) {
    var angular = require('angular');
    require("pagination");
    require("angular-ui");
    var dialog = require("dialogplus");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var datepicker = require("datepicker");
    var fundCtrl = require('/public/js/myservice/contract/editinc/receivable-fund-ctrl');
    var invoiceCtrl = require('/public/js/myservice/contract/editinc/receivable-invoice-ctrl');
    var refundCtrl = require('/public/js/myservice/contract/editinc/receivable-refund-ctrl');
    require('/public/js/myservice/common/row-toolbar');
    require('/public/js/myservice/contract/contract-common');

    angular.module('ContractReceivable', ['ngUI', 'ContractReceivableFund', 'rowToolbar', 'ContractCommonService', 'ContractReceivableInvoice', 'ContractReceivableRefund'])
        .controller('contractReceivableCtrl', ['$scope', 'receivableFundService', 'contractCommonService', '$routeParams', 'receivableInvoiceService', 'receivableRefundService',
            function ($scope, receivableFundService, contractCommonService, $routeParams, receivableInvoiceService, receivableRefundService) {
                $scope.receivableFundService = receivableFundService;
                $scope.receivableInvoiceService = receivableInvoiceService;
                $scope.receivableRefundService = receivableRefundService;
                $scope.title = 'receivable edit';
                $scope.contractBaseInfo = {};

                var contractId = $routeParams.id;
                //获取合同信息
                contractCommonService.getContract(contractId, function (data) {
                    $scope.contractBaseInfo = data.contract;
                    $scope.$applyAsync();
                });


                // 是否已认证
                $scope.ddlConfigIsAuth = {
                    allowClear: false,
                    data: [],
                    placeholder: '是否已认证'
                };
                $scope.ddlConfigIsAuth.data =[
                    {id: 1, text: '是'},
                    {id: 0, text: '否'},
                ];

                // 是否已认证
                $scope.ddlConfigIsGloden = {
                    allowClear: false,
                    data: [],
                    placeholder: '是否金牌'
                };
                $scope.ddlConfigIsGloden.data =[
                    {id: 1, text: '是'},
                    {id: 0, text: '否'},
                ];

                $scope.contractTypes = {
                    '开发商SaaS产品': 1,
                    '开发商线下活动': 2,
                    '供应商考察报告': 3,
                    '云采购会员': 4,
                    '供应商移动工程协同': 5,
                    '云采购采宝': 6,
                    '供应商线下活动': 7
                };
                $scope.contractBaseInfo.busnisseType = $scope.contractTypes[$routeParams.contractType];
                //$scope.contractBaseInfo.busnisseType = $scope.contractTypes[$scope.contractBaseInfo.business_type];
                console.log($scope.contractBaseInfo.busnisseType);

                //获取应收信息
                contractCommonService.getContractUnifiedInfo(contractId, function (data) {
                    $scope.receivableInfo = data;
                    //if($scope.contractBaseInfo.busnisseType == 7) {
                    var amount = 0;
                    $.each($scope.receivableInfo.invoices, function (idx, d) {
                        if(d.invoice_code != null && d.invoice_code != '') {
                            amount += parseFloat(d.invoice_amount);
                        }
                    });
                    $.each($scope.receivableInfo.payments, function (idxx, dd) {
                        dd.is_remark_show = false;
                        dd.remark = dd.remark == null ? '暂无' : dd.remark;
                    });
                    $scope.receivableInfo.summary.billingAmount = amount;
                    //}
                    $scope.$applyAsync();
                });

                // 获取收入信息(合同业务类型为供应商移动工程协同或云采购采宝或供应商线下活动时)
                if ($scope.contractBaseInfo.busnisseType == 5 || $scope.contractBaseInfo.busnisseType == 6) {
                    contractCommonService.getPayInfoByContractId(contractId, function (data) {
                        $scope.receivedInfo = data;
                        $scope.$applyAsync();
                    });
                }

                if ($scope.contractBaseInfo.busnisseType == 7) {
                    contractCommonService.getSuppliersPaymentByContractId(contractId, function (data) {
                        $scope.receivedInfo = data;
                        $scope.$applyAsync();
                    });
                }

                //款项回写刷新
                $scope.reloadFunds = function () {
                    //获取应收信息
                    contractCommonService.getContractUnifiedInfo(contractId, function (data) {
                        $scope.receivableInfo.receivables = data.receivables;
                        $scope.$applyAsync();
                    });
                };

                //新增发票回写刷新
                $scope.reloadInvoices = function () {
                    //获取应收信息
                    contractCommonService.getContractUnifiedInfo(contractId, function (data) {
                        $scope.receivableInfo = data;
                        //if($scope.contractBaseInfo.busnisseType == 7) {
                        var amount = 0;
                        $.each($scope.receivableInfo.invoices, function (idx, d) {
                            if(d.invoice_code != null && d.invoice_code != '') {
                                amount += parseFloat(d.invoice_amount);
                            }
                        });
                        $scope.receivableInfo.summary.billingAmount = amount;
                        //}
                        $scope.$applyAsync();
                    });
                };

                //新增回款回写刷新
                $scope.reloadRefund = function () {
                    //获取应收信息
                    contractCommonService.getContractUnifiedInfo(contractId, function (data) {
                        $scope.receivableInfo = data;
                        $scope.$applyAsync();
                    });
                };

                $scope.exportSupplierPaymentModel = function() {
                    contractCommonService.ExportSupplierPaymentModel(function() {
                        //
                    });
                };

                $scope.importInvoiceList = function() {
                    $('#importInvoiceList').fileupload({
                        dataType: 'json',
                        url: api_prefix + "contract/import-invoice-list-execl&contract_id=" + $routeParams.id,
                        acceptFileTypes: /(\.|\/)(xls?x)$/i,
                        maxFileSize: 10000000,
                        done: function (e, data) {
                            var res = data.result;
                            if(res.retCode == '0') {
                                alert('导入发票成功');
                                location.reload();
                            } else {
                                alert(res.errMsg);
                            }
                        },
                        fail: function(e, data) {
                            alert('系统维护，请稍候重试');
                        }
                    });
                };

                $scope.exportCaibaoInvoce = function () {
                    util.confirm('确定要导出数据吗？', {
                        ok: function () {
                            var parms = {contractid:contractId};
                            var url = api_prefix + '/contract/export-caibao-invoice';
                            util.download(url, parms);
                        }
                    });
                }

                $scope.importSupplierPayment = function () {
                    $('#importSupplierPayment').fileupload({
                        dataType: 'json',
                        url: api_prefix + "contract/import-supplier-payment-list-execl&contract_id=" + $routeParams.id,
                        acceptFileTypes: /(\.|\/)(xls?x)$/i,
                        maxFileSize: 10000000,
                        done: function (e, data) {
                            var res = data.result;
                            if(res.retCode == '0'){
                                alert('导入付款成功');
                                location.reload();
                            }else{
                                alert(res.errMsg);
                            }
                        },
                        fail: function(e, data) {
                            alert('系统维护，请稍候重试');
                        }
                    });
                };

                $scope.newPayinfo = function () {
                    var items = $scope.receivedInfo;
                    var id = items.length ? items[0].id + 1 : 1;

                    var newinfo = {
                        id:id,
                        contract_id:contractId,
                        username:'',
                        company_name:'',
                        is_auth:'',
                        is_gloden:'',
                        payamount:'',
                        deduction:'',
                        deduction_orderid:'',
                        payway:'',
                        sign_up_time:'',
                        invoice_code:'',
                        editMode: 1
                    };
                    items.unshift(newinfo);
                };
                
                $scope.cancelPayinfo = function (item,idx) {
                    if(item.editMode == 1){
                        var items = $scope.receivedInfo;
                        items.splice(idx,1);
                    }else{
                        angular.extend(item, item.orginalData);
                        item.editMode = 0;
                    }
                };
                
                $scope.editPayinfo = function (item,idx) {
                    item.orginalData = angular.copy(item);
                    item.editMode = 2;
                };
                
                $scope.savePayinfo = function (item) {
                    if (!item.username || item.username == '') {
                        util.alert('请填写姓名!');
                        return;
                    }
                    if (!item.company_name || item.company_name == '') {
                        util.alert('请填写公司名称!');
                        return;
                    }

                    var url = api_prefix + 'contract/save-contract-suppliers-payment';
                    $scope.contractBaseInfo.balance_amount = $("#sumBalanceAmount").text();
                    var post_data = {paymentInfo: item};
                    $.ajax({
                        url: url,
                        type: 'post',
                        dataType: 'json',
                        data: post_data,
                        success: function (res) {
                            if (res.retCode == "0") {
                                util.alert('保存成功');
                                contractCommonService.getSuppliersPaymentByContractId(contractId, function (data) {
                                    $scope.receivedInfo = data;
                                    $scope.$applyAsync();
                                });
                            } else {
                                util.alert(res.errMsg);
                            }
                        },
                        error: function () {
                            util.alert('系统维护，请稍候重试！');
                        }
                    });
                };
            }]);
});